var express = require('express');
var session = require('express-session');
var cookiesUtils = require('./utils/cookies-utils');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//这里传入了一个密钥加session id
app.use(cookieParser('secret'));
// 使用 session 中间件
app.use(session({
    secret : 'secret', // 对session id 相关的cookie 进行签名
    resave : true,
    saveUninitialized: false, // 是否保存未初始化的会话
    cookie : {
        maxAge : 1000 * 60 * 3, // 设置 session 的有效时间，单位毫秒
    },
}));
//app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function (req, res, next) {
    //res.setHeader('Set-Cookie', cookiesUtils.serialize('isVisit', '0'));
    console.log(JSON.stringify('session:' + JSON.stringify(req.session)));
    if(req.session.authen != undefined && req.session.authen.isLogin) {
        next();
    } else {
        console.log('用户未登录！！');
        //解析用户请求路径
        var arr = req.url.split('/');
        console.log('请求路径拆分：' + JSON.stringify(arr));
        //去除get请求携带的参数
        for (var i = 0; i < arr.length; i++) {
            arr[i] = arr[i].split('?')[0];
        }

        if (arr.length > 1) {
            if (req.url === '/auth/login' || (arr[1] === 'auth' && arr[2] === 'doLogin') || arr[1] === 'api' || arr[1] === 'login_commit'||arr[1] === 'video') {
                next();
            } else {
                console.log('intercept：用户未登录执行登录拦截，路径为：' + arr[1]);
                res.redirect('/auth/login');  // 将用户重定向到登录页面
                res.end();
            }
        }
    }
});

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
